import yaml
from pathlib import Path

# YAML 文件路径
storage_file = Path("account_data.yaml")


# 初始化存储
def load_storage():
    if not storage_file.exists():
        return {}
    with open(storage_file, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}


def save_storage(data):
    with open(storage_file, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True, default_flow_style=False)


def track_price_changes(new_data):
    # 加载存储数据
    storage = load_storage()

    added_accounts = []
    price_changed_accounts = []

    for account in new_data:
        account_data = {
            "price": [account[1]],
            "character": account[2],
            "weapon5_num": account[3],
        }

        account_id = account[0]

        if account_id not in storage:
            # 新账号，直接添加
            storage[account_id] = account_data
            added_accounts.append(account_id)
        else:
            # 已存在账号，检查价格是否发生变化
            if account[1] not in storage[account_id]["price"]:
                storage[account_id]["price"].append(account[1])
                price_changed_accounts.append(account_id)

    # 保存更新后的数据
    save_storage(storage)

    return added_accounts, price_changed_accounts


def query_price_trend(
    id: str, show_account_info: bool = False, yaml_file: str = "account_data.yaml"
):
    # 读取YAML文件
    with open(yaml_file, "r", encoding="utf-8") as file:
        data = yaml.safe_load(file)

    # 检查id是否存在
    if id in data:
        account_info = data[id]

        # 输出价格变化趋势
        price_changes = account_info["price"]
        print(f"价格变化趋势: {price_changes}")

        # 如果选择打印账户信息，打印相关信息
        if show_account_info:
            character_info = account_info["character"]
            weapon5_num = account_info["weapon5_num"]
            print(f"账户信息：")
            print(f"账号ID: {id}")
            print(f"角色: {character_info}")
            print(f"五星武器数量: {weapon5_num}")
    else:
        print(f"未找到账号ID: {id}")
